package com.ujs.shc.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

public class UtilImage {

    /**
     *
     * @param request
     * @param file
     * @param targetDir "upload/goods/"
     * @return
     * @throws IOException
     */
    public static String copyFile(HttpServletRequest request, MultipartFile file,String targetDir)throws IOException {

        String webAppPath = request.getServletContext().getRealPath("/").replace("\\","/");
        String path = webAppPath + targetDir;
//        System.out.println("path:"+ path);
        File pathDir = new File(path);
        if(! pathDir.exists()){
            pathDir.mkdir();
        }
//        获取文件名
        String fileName = file.getOriginalFilename();
//        取得后缀名
        String extName = fileName.substring(fileName.lastIndexOf(".")+1);
//        取别名 防止同名
        String newFileName = String.valueOf(System.currentTimeMillis()) + "." + extName;

        File saveFile = new File(path, newFileName);

            //核心 将multipart拷贝到文件中
       file.transferTo(saveFile);

       return saveFile.getName();
    }

}
